<?php

namespace Tbf\Bundle\PackageBundle\RelationPackage;

use Tbf\Bundle\PackageBundle\ActionInterface;
use Tbf\Bundle\TbfBundle\Controller\TbfController;

/**
 * 总数
 * ManyToMany列出关系,第2个必须要有指回第1个的属性,顺序非常重要
 */
class TotalAction extends TbfController implements ActionInterface
{
    /** @var  RelationControllerConfig */
    protected $config;
    public function setConfig(RelationControllerConfig $config)
    {
        $this->config = $config;
    }
    public function execute($input)
    {
        $err = $this->checkParameterExist($input,array($this->config->getIdName('first')));
        if ($err!==null) {
            return array(null,$err);
        }
        $qb = $this->getDM()->createQueryBuilder()
            ->from($this->config->getEntityClassName('second'),'second')
            ->join('second.'.$this->config->getPropertyNameToAnother('second'),'first')
            ->where('first.id=:first_id')
            ->select('count(second)')
            ->setParameter('first_id',$input[$this->config->getIdName('first')]);
        $total = $qb->getQuery()->getSingleScalarResult();

        return array($total,null);
    }

}
